<template>
  <div class="admin-reports">
    <el-card class="header-card">
      <template #header>
        <div class="card-header">
          <span class="title">
            <el-icon><DataAnalysis /></el-icon>
            管理员数据报表
          </span>
          <div class="header-actions">
            <el-date-picker
              v-model="dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              @change="handleDateRangeChange"
              clearable
            />
            <el-button type="primary" :icon="Refresh" @click="refreshData" :loading="loading">
              刷新数据
            </el-button>
            <el-button type="success" @click="generateReports" :loading="generateLoading">
              生成总报表
            </el-button>
            <el-button type="info" @click="showSummaryReports">
              查看总报表
            </el-button>
          </div>
        </div>
      </template>
      
      <!-- 管理员总数据报表 -->
      <div v-if="summaryReports.visible" class="summary-reports-section">
        <h3 class="section-title">
                          <el-icon><Document /></el-icon>
          管理员总数据报表
          <el-button type="text" @click="summaryReports.visible = false" style="float: right;">
            <el-icon><Close /></el-icon>
          </el-button>
        </h3>
        
        <div v-if="summaryReports.latestReport" class="summary-report-card">
          <div class="report-header">
            <span class="report-date">报表日期：{{ summaryReports.latestReport.reportDate }}</span>
            <span class="report-time">
              更新时间：{{ formatDateTime(summaryReports.latestReport.updateTime) }}
            </span>
          </div>
          
          <div class="summary-stats">
            <div class="summary-stat-item">
              <div class="stat-label">套餐收入</div>
              <div class="stat-value">¥{{ formatNumber(summaryReports.latestReport.packageRevenue) }}</div>
            </div>
            <div class="summary-stat-item">
              <div class="stat-label">购物收入</div>
              <div class="stat-value">¥{{ formatNumber(summaryReports.latestReport.purchaseRevenue) }}</div>
            </div>
            <div class="summary-stat-item">
              <div class="stat-label">充值收入</div>
              <div class="stat-value">¥{{ formatNumber(summaryReports.latestReport.rechargeRevenue) }}</div>
            </div>
            <div class="summary-stat-item highlight">
              <div class="stat-label">总收入</div>
              <div class="stat-value">¥{{ formatNumber(summaryReports.latestReport.totalRevenue) }}</div>
            </div>
            <div class="summary-stat-item">
              <div class="stat-label">总成本</div>
              <div class="stat-value">¥{{ formatNumber(summaryReports.latestReport.totalCost) }}</div>
            </div>
            <div class="summary-stat-item highlight">
              <div class="stat-label">总利润</div>
              <div class="stat-value">¥{{ formatNumber(summaryReports.latestReport.totalProfit) }}</div>
            </div>
            <div class="summary-stat-item">
              <div class="stat-label">利润率</div>
              <div class="stat-value">{{ formatNumber(summaryReports.latestReport.profitMargin) }}%</div>
            </div>
            <div class="summary-stat-item">
              <div class="stat-label">总交易数</div>
              <div class="stat-value">{{ summaryReports.latestReport.totalTransactions }}</div>
            </div>
          </div>
        </div>
        
        <div v-else-if="summaryReports.todayStatistics" class="summary-today-stats">
          <div class="report-header">
            <span class="report-date">今日实时数据</span>
            <span class="report-note">暂无历史报表，显示今日实时统计</span>
          </div>
          
          <div class="summary-stats">
            <div class="summary-stat-item">
              <div class="stat-label">套餐收入</div>
              <div class="stat-value">¥{{ formatNumber(summaryReports.todayStatistics.packageRevenue) }}</div>
            </div>
            <div class="summary-stat-item">
              <div class="stat-label">购物收入</div>
              <div class="stat-value">¥{{ formatNumber(summaryReports.todayStatistics.purchaseRevenue) }}</div>
            </div>
            <div class="summary-stat-item">
              <div class="stat-label">充值收入</div>
              <div class="stat-value">¥{{ formatNumber(summaryReports.todayStatistics.rechargeRevenue) }}</div>
            </div>
            <div class="summary-stat-item highlight">
              <div class="stat-label">总收入</div>
              <div class="stat-value">¥{{ formatNumber(summaryReports.todayStatistics.totalRevenue) }}</div>
            </div>
          </div>
        </div>
        
        <div class="summary-actions">
          <el-button type="primary" @click="loadSummaryReportsHistory">查看历史报表</el-button>
          <el-button type="success" @click="generateReports">重新生成报表</el-button>
        </div>
      </div>
      
      <!-- 统计卡片 -->
      <div class="stats-cards">
        <div class="stat-card">
          <div class="stat-icon revenue">
            <el-icon><Wallet /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-value">¥{{ formatNumber(statisticsData.totalRevenue) }}</div>
            <div class="stat-label">平台总收入</div>
            <div class="stat-desc">套餐+购物+充值收入</div>
          </div>
        </div>
        
        <div class="stat-card">
          <div class="stat-icon cost">
            <el-icon><Money /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-value">¥{{ formatNumber(statisticsData.totalCost) }}</div>
            <div class="stat-label">平台总成本</div>
            <div class="stat-desc">运营成本</div>
          </div>
        </div>
        
        <div class="stat-card">
          <div class="stat-icon profit">
            <el-icon><TrendCharts /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-value">¥{{ formatNumber(statisticsData.totalProfit) }}</div>
            <div class="stat-label">平台总利润</div>
            <div class="stat-desc">利润率: {{ formatNumber(statisticsData.profitMargin) }}%</div>
          </div>
        </div>
        
        <div class="stat-card">
          <div class="stat-icon transactions">
            <el-icon><ShoppingCart /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-value">{{ statisticsData.totalTransactions }}</div>
            <div class="stat-label">总交易数</div>
            <div class="stat-desc">订单+购买记录</div>
          </div>
        </div>
      </div>
    </el-card>

    <!-- 图表区域 -->
    <div class="charts-container">
      <!-- 收入趋势图 -->
      <el-card class="chart-card">
        <template #header>
          <div class="chart-header">
            <span>收入趋势分析</span>
            <el-radio-group v-model="timeType" @change="handleTimeTypeChange">
              <el-radio-button label="week">近7天</el-radio-button>
              <el-radio-button label="month">近30天</el-radio-button>
              <el-radio-button label="quarter">近3个月</el-radio-button>
            </el-radio-group>
          </div>
        </template>
        <div ref="revenueChartRef" class="chart-container"></div>
      </el-card>

      <!-- 成本分析图 -->
      <el-card class="chart-card">
        <template #header>
          <span>成本分析</span>
        </template>
        <div ref="costChartRef" class="chart-container"></div>
      </el-card>
    </div>

    <!-- 利润分析 -->
    <el-card class="profit-analysis-card">
      <template #header>
        <span>利润分析</span>
      </template>
      
      <div class="profit-analysis-content">
        <div class="profit-item">
          <div class="profit-label">套餐业务利润</div>
          <div class="profit-value">¥{{ formatNumber(profitData.packageProfit) }}</div>
          <div class="profit-margin">利润率: {{ formatNumber(profitData.packageProfitMargin) }}%</div>
        </div>
        
        <div class="profit-item">
          <div class="profit-label">购物业务利润</div>
          <div class="profit-value">¥{{ formatNumber(profitData.purchaseProfit) }}</div>
          <div class="profit-margin">利润率: {{ formatNumber(profitData.purchaseProfitMargin) }}%</div>
        </div>
        
        <div class="profit-item">
          <div class="profit-label">充值业务利润</div>
          <div class="profit-value">¥{{ formatNumber(profitData.rechargeProfit) }}</div>
          <div class="profit-margin">利润率: {{ formatNumber(profitData.rechargeProfitMargin) }}%</div>
        </div>
        
        <div class="profit-item total">
          <div class="profit-label">总利润</div>
          <div class="profit-value">¥{{ formatNumber(profitData.totalProfit) }}</div>
          <div class="profit-margin">总利润率: {{ formatNumber(profitData.profitMargin) }}%</div>
        </div>
      </div>
    </el-card>


  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { 
  DataAnalysis, 
  Refresh, 
  Wallet, 
  ShoppingCart, 
  Money,
  TrendCharts,
  Document,
  Close
} from '@element-plus/icons-vue'
import * as echarts from 'echarts'
import { 
  getAdminReportsData, 
  getAdminSummaryReports, 
  generateAdminReports,
  getAdminReportsHistory 
} from '@/api/adminReports'

// 响应式数据
const loading = ref(false)
const generateLoading = ref(false)
const dateRange = ref([])
const timeType = ref('month')

// 管理员总数据报表
const summaryReports = reactive({
  visible: false,
  latestReport: null,
  todayStatistics: null,
  message: ''
})

// 统计数据
const statisticsData = reactive({
  totalRevenue: 0,
  totalCost: 0,
  totalProfit: 0,
  profitMargin: 0,
  totalTransactions: 0
})

// 利润分析数据
const profitData = reactive({
  packageProfit: 0,
  packageProfitMargin: 0,
  purchaseProfit: 0,
  purchaseProfitMargin: 0,
  rechargeProfit: 0,
  rechargeProfitMargin: 0,
  totalProfit: 0,
  profitMargin: 0
})



// 图表实例
let revenueChart = null
let costChart = null

// DOM引用
const revenueChartRef = ref(null)
const costChartRef = ref(null)

// 格式化数字
const formatNumber = (value) => {
  if (value === null || value === undefined) return '0'
  return Number(value).toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })
}

// 处理日期范围变化
const handleDateRangeChange = (dates) => {
  getReportsData()
}

// 处理时间类型变化
const handleTimeTypeChange = () => {
  getReportsData()
}

// 刷新数据
const refreshData = () => {
  getReportsData()
}

// 显示管理员总数据报表
const showSummaryReports = async () => {
  try {
    const response = await getAdminSummaryReports()
    
    if (response.code === 200) {
      const data = response.data
      summaryReports.latestReport = data.latestReport
      summaryReports.todayStatistics = data.todayStatistics
      summaryReports.message = data.message || ''
      summaryReports.visible = true
    } else {
      ElMessage.error(response.message || '获取管理员总数据报表失败')
    }
  } catch (error) {
    console.error('获取管理员总数据报表失败:', error)
    ElMessage.error('获取管理员总数据报表失败')
  }
}

// 生成管理员总数据报表
const generateReports = async () => {
  try {
    generateLoading.value = true
    
    const response = await generateAdminReports()
    
    if (response.code === 200) {
      ElMessage.success(response.data || '管理员总数据报表生成成功！')
      // 重新加载总数据报表
      if (summaryReports.visible) {
        await showSummaryReports()
      }
    } else {
      ElMessage.error(response.message || '生成管理员总数据报表失败')
    }
  } catch (error) {
    console.error('生成管理员总数据报表失败:', error)
    ElMessage.error('生成管理员总数据报表失败')
  } finally {
    generateLoading.value = false
  }
}

// 查看总数据报表历史
const loadSummaryReportsHistory = async () => {
  try {
    const response = await getAdminReportsHistory({ page: 1, size: 10 })
    
    if (response.code === 200) {
      console.log('历史报表数据:', response.data)
      ElMessage.success('历史报表数据加载成功，请查看控制台')
      // 这里可以添加一个对话框来显示历史数据
    } else {
      ElMessage.error(response.message || '获取历史报表数据失败')
    }
  } catch (error) {
    console.error('获取历史报表数据失败:', error)
    ElMessage.error('获取历史报表数据失败')
  }
}

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return ''
  return new Date(dateTime).toLocaleString('zh-CN')
}

// 获取报表数据
const getReportsData = async () => {
  try {
    loading.value = true
    
    const params = {
      timeType: timeType.value
    }
    
    // 临时注释掉日期范围参数，获取所有历史数据
    // if (dateRange.value && dateRange.value.length === 2) {
    //   params.startDate = dateRange.value[0]
    //   params.endDate = dateRange.value[1]
    // }
    
    const response = await getAdminReportsData(params)
    
    if (response.code === 200) {
      const data = response.data
      
      // 更新统计数据
      Object.assign(statisticsData, data.statistics)
      
      // 更新利润分析数据
      Object.assign(profitData, data.profitData)
      
      // 更新图表
      updateRevenueChart(data.revenueData)
      updateCostChart(data.costData)
      
    } else {
      ElMessage.error(response.message || '获取报表数据失败')
    }
  } catch (error) {
    console.error('获取报表数据失败:', error)
    ElMessage.error('获取报表数据失败')
  } finally {
    loading.value = false
  }
}

// 初始化收入趋势图
const initRevenueChart = () => {
  if (!revenueChartRef.value) return
  
  revenueChart = echarts.init(revenueChartRef.value)
  
  const option = {
    title: {
      text: '收入、成本、利润趋势',
      left: 'center',
      textStyle: {
        fontSize: 14,
        color: '#666'
      }
    },
    tooltip: {
      trigger: 'axis',
      formatter: (params) => {
        let result = `${params[0].axisValue}<br/>`
        params.forEach(param => {
          result += `${param.seriesName}: ¥${formatNumber(param.value)}<br/>`
        })
        return result
      }
    },
    legend: {
      data: ['收入', '成本', '利润'],
      top: 30
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      top: '15%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: [],
      axisLabel: {
        rotate: 45
      }
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        formatter: (value) => `¥${formatNumber(value)}`
      }
    },
    series: [
      {
        name: '收入',
        type: 'line',
        smooth: true,
        data: [],
        itemStyle: { color: '#409EFF' },
        areaStyle: {
          color: {
            type: 'linear',
            x: 0, y: 0, x2: 0, y2: 1,
            colorStops: [
              { offset: 0, color: 'rgba(64, 158, 255, 0.3)' },
              { offset: 1, color: 'rgba(64, 158, 255, 0.1)' }
            ]
          }
        }
      },
      {
        name: '成本',
        type: 'line',
        smooth: true,
        data: [],
        itemStyle: { color: '#F56C6C' }
      },
      {
        name: '利润',
        type: 'line',
        smooth: true,
        data: [],
        itemStyle: { color: '#67C23A' }
      }
    ]
  }
  
  revenueChart.setOption(option)
}

// 初始化成本分析图
const initCostChart = () => {
  if (!costChartRef.value) return
  
  costChart = echarts.init(costChartRef.value)
  
  const option = {
    title: {
      text: '成本构成分析',
      left: 'center',
      textStyle: {
        fontSize: 14,
        color: '#666'
      }
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: ¥{c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      top: 'middle'
    },
    series: [
      {
        name: '成本构成',
        type: 'pie',
        radius: ['40%', '70%'],
        center: ['60%', '50%'],
        avoidLabelOverlap: false,
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '18',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: []
      }
    ]
  }
  
  costChart.setOption(option)
}

// 更新收入趋势图
const updateRevenueChart = (revenueData) => {
  if (!revenueChart || !revenueData) return
  
  const option = {
    xAxis: {
      data: revenueData.dates || []
    },
    series: [
      {
        name: '收入',
        data: revenueData.revenueValues || []
      },
      {
        name: '成本',
        data: revenueData.costValues || []
      },
      {
        name: '利润',
        data: revenueData.profitValues || []
      }
    ]
  }
  
  revenueChart.setOption(option)
}

// 更新成本分析图
const updateCostChart = (costData) => {
  if (!costChart || !costData) return
  
  const data = [
    { value: costData.packageCost || 0, name: '套餐成本' },
    { value: costData.purchaseCost || 0, name: '购物成本' },
    { value: costData.rechargeCost || 0, name: '充值成本' }
  ]
  
  const option = {
    series: [
      {
        data: data
      }
    ]
  }
  
  costChart.setOption(option)
}

// 处理窗口大小变化
const handleResize = () => {
  revenueChart?.resize()
  costChart?.resize()
}

// 页面挂载
onMounted(() => {
  nextTick(() => {
    initRevenueChart()
    initCostChart()
    getReportsData()
    
    // 监听窗口大小变化
    window.addEventListener('resize', handleResize)
  })
})

// 页面卸载时清理
onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
  revenueChart?.dispose()
  costChart?.dispose()
})
</script>

<style scoped>
.admin-reports {
  padding: 20px;
}

.header-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.title {
  font-size: 18px;
  font-weight: bold;
  display: flex;
  align-items: center;
  gap: 8px;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 12px;
}

/* 统计卡片样式 */
.stats-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 20px;
  margin-top: 20px;
}

.stat-card {
  display: flex;
  align-items: center;
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: transform 0.2s;
}

.stat-card:hover {
  transform: translateY(-2px);
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 16px;
  font-size: 24px;
  color: #fff;
}

.stat-icon.revenue {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.stat-icon.cost {
  background: linear-gradient(135deg, #ff9a9e 0%, #fecfef 100%);
}

.stat-icon.profit {
  background: linear-gradient(135deg, #a8edea 0%, #fed6e3 100%);
}

.stat-icon.transactions {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.stat-content {
  flex: 1;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #333;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 14px;
  color: #666;
  margin-bottom: 2px;
}

.stat-desc {
  font-size: 12px;
  color: #999;
}

/* 图表区域 */
.charts-container {
  display: grid;
  grid-template-columns: 2fr 1fr;
  gap: 20px;
  margin-bottom: 20px;
}

.chart-card {
  min-height: 400px;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart-container {
  height: 350px;
  width: 100%;
}

/* 利润分析 */
.profit-analysis-card {
  margin-bottom: 20px;
}

.profit-analysis-content {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
}

.profit-item {
  text-align: center;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
}

.profit-item.total {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.profit-label {
  font-size: 14px;
  color: #666;
  margin-bottom: 8px;
}

.profit-item.total .profit-label {
  color: rgba(255, 255, 255, 0.9);
}

.profit-value {
  font-size: 20px;
  font-weight: bold;
  color: #333;
  margin-bottom: 4px;
}

.profit-item.total .profit-value {
  color: white;
}

.profit-margin {
  font-size: 12px;
  color: #999;
}

.profit-item.total .profit-margin {
  color: rgba(255, 255, 255, 0.8);
}



/* 管理员总数据报表样式 */
.summary-reports-section {
  margin-bottom: 20px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
  border-left: 4px solid #409EFF;
}

.section-title {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 20px;
  color: #333;
  font-size: 16px;
  font-weight: bold;
}

.summary-report-card {
  background: white;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.summary-today-stats {
  background: white;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.report-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 12px;
  border-bottom: 1px solid #eee;
}

.report-date {
  font-size: 16px;
  font-weight: bold;
  color: #409EFF;
}

.report-time {
  font-size: 12px;
  color: #666;
}

.report-note {
  font-size: 12px;
  color: #E6A23C;
}

.summary-stats {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
  gap: 16px;
}

.summary-stat-item {
  text-align: center;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 6px;
  border: 1px solid #eee;
  transition: all 0.2s;
}

.summary-stat-item:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.summary-stat-item.highlight {
  background: linear-gradient(135deg, #409EFF 0%, #36A3F7 100%);
  color: white;
  border: none;
}

.summary-stat-item .stat-label {
  font-size: 12px;
  color: #666;
  margin-bottom: 8px;
}

.summary-stat-item.highlight .stat-label {
  color: rgba(255, 255, 255, 0.9);
}

.summary-stat-item .stat-value {
  font-size: 18px;
  font-weight: bold;
  color: #333;
}

.summary-stat-item.highlight .stat-value {
  color: white;
}

.summary-actions {
  display: flex;
  gap: 12px;
  justify-content: center;
}

@media (max-width: 768px) {
  .summary-stats {
    grid-template-columns: repeat(2, 1fr);
  }
  
  .summary-actions {
    flex-direction: column;
  }
}

@media (max-width: 768px) {
  .charts-container {
    grid-template-columns: 1fr;
  }
  
  .stats-cards {
    grid-template-columns: 1fr;
  }
  
  .profit-analysis-content {
    grid-template-columns: 1fr;
  }
}
</style> 